package io.potato.ts.service;

import io.potato.core.util.TableUtil;
import io.potato.ts.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 数据清理服务, 删除过期的数据
 */
@Service
@Transactional
@Slf4j
public class DataCleanService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final String DEL_WEB_SENDED_SQL = "DELETE FROM sms_sended_record WHERE send_time < ?";

    /**
     * 删除短信状态报告
     */
    private static final String DEL_STATUS_REPORT_SQL = "DELETE FROM sms_status_report WHERE created_at < ? ";

    /**
     * 删除已成功发送的记录
     */
    private static final String DEL_SENDING_SQL = "DELETE FROM %s WHERE status = 1 AND send_time < ? ";

    /**
     * 删除长时间没有发送成功的记录
     */
    private static final String DEL_SENDING_SQL2 = "DELETE FROM %s WHERE status <> 1 AND send_time < ? ";

    /**
     * 删除过期的已发送记录
     */
    public void deleteWebSendedRecord() {
        LocalDateTime delTime = LocalDateTime.now().minusDays(100);
        int rows = jdbcTemplate.update(DEL_WEB_SENDED_SQL, delTime);
        log.info("delete " + rows + " for table sms_sended_record");
    }

    /**
     * 删除过期的短信状态报告
     */
    public void deleteStatusReport() {
        LocalDateTime delTime = LocalDateTime.now().minusDays(3);
        int rows = jdbcTemplate.update(DEL_STATUS_REPORT_SQL, delTime);
        log.info("delete " + rows + " for table sms_status_report");
    }

    /**
     * 删除过期的待发送记录
     */
    public void deleteSendingRecord() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime delTime = now.minusHours(24);
        LocalDateTime delTime2 = now.minusDays(7);
        String tableName;

        // 删除web短信
        tableName = TableUtil.getSendingRecordTable(Constants.SENDER_TYPE_WEB, 0);
        deleteSendingRecord(tableName, delTime, delTime2);

        // 删除API短信
        for (int i = 0; i < 20; i++) {
            tableName = TableUtil.getSendingRecordTable(Constants.SENDER_TYPE_API, i);
            deleteSendingRecord(tableName, delTime, delTime2);
        }
    }

    private void deleteSendingRecord(String tableName, LocalDateTime delTime, LocalDateTime delTime2) {
        int rows;
        rows = jdbcTemplate.update(String.format(DEL_SENDING_SQL, tableName), delTime);
        log.info("delete " + rows + " for table " + tableName);
        rows = jdbcTemplate.update(String.format(DEL_SENDING_SQL2, tableName), delTime2);
        log.info("delete " + rows + " for table " + tableName);
    }

}
